// Token管理工具
class TokenManager {
  constructor() {
    this.tokenKey = 'token';
    this.userInfoKey = 'userInfo';
    this.refreshTokenKey = 'refreshToken';
  }

  // 保存token
  setToken(token) {
    uni.setStorageSync(this.tokenKey, token);
  }

  // 获取token
  getToken() {
    return uni.getStorageSync(this.tokenKey);
  }

  // 保存用户信息
  setUserInfo(userInfo) {
    uni.setStorageSync(this.userInfoKey, userInfo);
  }

  // 获取用户信息
  getUserInfo() {
    return uni.getStorageSync(this.userInfoKey);
  }

  // 清除所有认证信息
  clearAuth() {
    uni.removeStorageSync(this.tokenKey);
    uni.removeStorageSync(this.userInfoKey);
    uni.removeStorageSync(this.refreshTokenKey);
  }

  // 检查是否已登录
  isLoggedIn() {
    const token = this.getToken();
    return token && token.trim() !== '';
  }

  // 检查token是否即将过期
  async checkTokenExpiration() {
    try {
      const token = this.getToken();
      if (!token) {
        return { isExpired: true, isExpiringSoon: false, timeLeft: 0 };
      }

      // 解析JWT token（不验证签名，只获取过期时间）
      const payload = this.parseJWT(token);
      if (!payload || !payload.exp) {
        return { isExpired: true, isExpiringSoon: false, timeLeft: 0 };
      }

      const now = Math.floor(Date.now() / 1000);
      const exp = payload.exp;
      const timeLeft = exp - now;

      // 检查是否已过期
      if (timeLeft <= 0) {
        return { isExpired: true, isExpiringSoon: false, timeLeft: 0 };
      }

      // 检查是否即将过期（30分钟内）
      const isExpiringSoon = timeLeft <= 30 * 60; // 30分钟

      return {
        isExpired: false,
        isExpiringSoon,
        timeLeft,
        expiresAt: new Date(exp * 1000)
      };
    } catch (error) {
      console.error('检查token过期时间失败:', error);
      return { isExpired: true, isExpiringSoon: false, timeLeft: 0 };
    }
  }

  // 解析JWT token（仅用于获取过期时间，不验证签名）
  parseJWT(token) {
    try {
      const base64Url = token.split('.')[1];
      const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
      const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
      }).join(''));

      return JSON.parse(jsonPayload);
    } catch (error) {
      console.error('解析JWT token失败:', error);
      return null;
    }
  }

  // 自动刷新token
  async autoRefreshToken() {
    try {
      const tokenInfo = await this.checkTokenExpiration();
      
      // 如果token已过期，无法刷新
      if (tokenInfo.isExpired) {
        return false;
      }

      // 如果token即将过期，尝试刷新
      if (tokenInfo.isExpiringSoon) {
        console.log('Token即将过期，尝试自动刷新');
        return await this.refreshToken();
      }

      return true;
    } catch (error) {
      console.error('自动刷新token失败:', error);
      return false;
    }
  }

  // 刷新token
  async refreshToken() {
    try {
      const token = this.getToken();
      if (!token) {
        return false;
      }

      const response = await uni.request({
        url: 'http://localhost:8080/user/refresh-token',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.statusCode === 200 && response.data.code === 200) {
        const newToken = response.data.data;
        this.setToken(newToken);
        console.log('Token刷新成功');
        return true;
      } else {
        console.log('Token刷新失败:', response.data.message);
        return false;
      }
    } catch (error) {
      console.error('刷新token失败:', error);
      return false;
    }
  }

  // 获取token状态信息
  getTokenStatus() {
    const token = this.getToken();
    if (!token) {
      return {
        hasToken: false,
        message: '未登录'
      };
    }

    try {
      const payload = this.parseJWT(token);
      if (!payload || !payload.exp) {
        return {
          hasToken: false,
          message: 'Token格式错误'
        };
      }

      const now = Math.floor(Date.now() / 1000);
      const exp = payload.exp;
      const timeLeft = exp - now;

      if (timeLeft <= 0) {
        return {
          hasToken: false,
          message: 'Token已过期'
        };
      }

      const minutesLeft = Math.floor(timeLeft / 60);
      const hoursLeft = Math.floor(minutesLeft / 60);
      const daysLeft = Math.floor(hoursLeft / 24);

      let timeMessage = '';
      if (daysLeft > 0) {
        timeMessage = `${daysLeft}天`;
      } else if (hoursLeft > 0) {
        timeMessage = `${hoursLeft}小时`;
      } else if (minutesLeft > 0) {
        timeMessage = `${minutesLeft}分钟`;
      } else {
        timeMessage = `${timeLeft}秒`;
      }

      return {
        hasToken: true,
        message: `Token有效，剩余${timeMessage}`,
        timeLeft,
        expiresAt: new Date(exp * 1000),
        isExpiringSoon: timeLeft <= 30 * 60 // 30分钟内过期
      };
    } catch (error) {
      return {
        hasToken: false,
        message: 'Token解析失败'
      };
    }
  }

  // 显示token状态
  showTokenStatus() {
    const status = this.getTokenStatus();
    
    if (status.hasToken && status.isExpiringSoon) {
      uni.showModal({
        title: '登录状态提醒',
        content: `您的登录状态将在${Math.floor(status.timeLeft / 60)}分钟后过期，建议及时保存数据`,
        showCancel: false,
        confirmText: '知道了'
      });
    } else if (!status.hasToken) {
      uni.showModal({
        title: '登录状态',
        content: status.message,
        showCancel: false,
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
    }
  }
}

// 创建实例
const tokenManager = new TokenManager();

// 导出
export default tokenManager;
